#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版蓝牙 Joycon 读取器
直接通过蓝牙读取 Joycon 数据

Author: Assistant
Date: 2024-12-19
"""

import subprocess
import time
import re
import json
from typing import Dict, Optional

class BluetoothJoyconReader:
    """蓝牙 Joycon 读取器"""
    
    def __init__(self):
        self.joycon_devices = []
        self.connected = False
        
    def scan_devices(self):
        """扫描 Joycon 设备"""
        print("扫描 Joycon 设备...")
        
        try:
            result = subprocess.run(['bluetoothctl', 'devices'], 
                                  capture_output=True, text=True, timeout=10)
            
            devices = []
            for line in result.stdout.split('\n'):
                if 'joy-con' in line.lower() or 'nintendo' in line.lower():
                    # 提取 MAC 地址和名称
                    match = re.search(r'Device\s+([A-F0-9:]+)\s+(.+)', line)
                    if match:
                        mac = match.group(1)
                        name = match.group(2).strip()
                        devices.append({'mac': mac, 'name': name})
                        print(f"发现设备: {name} ({mac})")
            
            self.joycon_devices = devices
            return len(devices) > 0
            
        except Exception as e:
            print(f"扫描设备失败: {e}")
            return False
    
    def check_connection(self):
        """检查连接状态"""
        print("检查连接状态...")
        
        connected_count = 0
        for device in self.joycon_devices:
            try:
                result = subprocess.run(['bluetoothctl', 'info', device['mac']], 
                                      capture_output=True, text=True, timeout=5)
                
                if 'Connected: yes' in result.stdout:
                    print(f"✅ {device['name']} 已连接")
                    connected_count += 1
                else:
                    print(f"❌ {device['name']} 未连接")
                    
            except Exception as e:
                print(f"检查 {device['name']} 连接状态失败: {e}")
        
        self.connected = connected_count > 0
        return self.connected
    
    def connect_devices(self):
        """连接设备"""
        print("尝试连接设备...")
        
        for device in self.joycon_devices:
            try:
                print(f"连接 {device['name']}...")
                result = subprocess.run(['bluetoothctl', 'connect', device['mac']], 
                                      capture_output=True, text=True, timeout=10)
                
                if 'Failed' in result.stderr:
                    print(f"❌ 连接 {device['name']} 失败: {result.stderr}")
                else:
                    print(f"✅ 连接 {device['name']} 成功")
                    
            except Exception as e:
                print(f"连接 {device['name']} 失败: {e}")
        
        # 等待连接建立
        print("等待连接建立...")
        time.sleep(5)
        return self.check_connection()
    
    def get_device_info(self) -> Dict:
        """获取设备信息"""
        info = {
            'devices': [],
            'connected': self.connected,
            'total_devices': len(self.joycon_devices)
        }
        
        for device in self.joycon_devices:
            try:
                result = subprocess.run(['bluetoothctl', 'info', device['mac']], 
                                      capture_output=True, text=True, timeout=5)
                
                device_info = {
                    'name': device['name'],
                    'mac': device['mac'],
                    'connected': 'Connected: yes' in result.stdout,
                    'paired': 'Paired: yes' in result.stdout,
                    'trusted': 'Trusted: yes' in result.stdout
                }
                
                info['devices'].append(device_info)
                
            except Exception as e:
                print(f"获取 {device['name']} 信息失败: {e}")
        
        return info
    
    def run(self):
        """运行主循环"""
        print("蓝牙 Joycon 读取器")
        print("="*40)
        
        # 扫描设备
        if not self.scan_devices():
            print("未发现 Joycon 设备")
            return
        
        # 检查连接
        if not self.check_connection():
            print("尝试连接设备...")
            if not self.connect_devices():
                print("连接失败")
                return
        
        print("开始监控设备状态...")
        print("按 Ctrl+C 退出")
        
        try:
            while True:
                info = self.get_device_info()
                
                print("\n" + "="*40)
                print(f"设备数量: {info['total_devices']}")
                print(f"连接状态: {'已连接' if info['connected'] else '未连接'}")
                
                for device in info['devices']:
                    status = "✅" if device['connected'] else "❌"
                    print(f"{status} {device['name']}")
                    print(f"    MAC: {device['mac']}")
                    print(f"    配对: {'是' if device['paired'] else '否'}")
                    print(f"    信任: {'是' if device['trusted'] else '否'}")
                
                time.sleep(2)
                
        except KeyboardInterrupt:
            print("\n程序已退出")

def main():
    """主函数"""
    reader = BluetoothJoyconReader()
    reader.run()

if __name__ == "__main__":
    main() 